export const genCode = () => {
  const min = Math.floor(Math.random() * 5 + 2);
  const repeatCount = Math.floor(Math.random() * 2 + 1);
  const max = min + 3;
  const createId = [];
  const numrepeatInfo = [];

  const userLen = Math.round(Math.random() * (max - min)) + min;

  for (let index = 0; index < userLen; index++) {
    createId.push(Math.ceil(Math.random() * 9));
  }

  // 1-9数字出现次数
  for (let i = 1; i < 10; i++) {
    numrepeatInfo.push({
      val: i,
      iCount: createId.filter((it) => it === i).length,
    });
  }

  // 数组查重 | 重复次数大于2的数字
  const userIdRepeatGtTwo = createId.reduce((repeatIdInfo, cv, ci, arr) => {
    // 是否有cv元素
    const findEd = repeatIdInfo.findIndex((it) => it.val === cv);
    if (findEd !== -1) return repeatIdInfo;

    // 当前数组信息
    const cvInfo = {
      repeatNumIndex: [],
      val: cv,
      replaceCount: null,
    };

    // cv重复的次数
    arr.forEach((it, iti) =>
      it === cv ? cvInfo.repeatNumIndex.push(iti) : '',
    );

    if (cvInfo.repeatNumIndex.length > repeatCount) {
      cvInfo.replaceCount = cvInfo.repeatNumIndex.length - repeatCount;
      repeatIdInfo.push(cvInfo);
    }

    return repeatIdInfo;
  }, []);

  if (userIdRepeatGtTwo.length) {
    userIdRepeatGtTwo.forEach((cv) => {
      // 替换的次数
      for (let index = 0; index < cv.replaceCount; index++) {
        const repMinCount = numrepeatInfo.sort((a, b) => a.count - b.count)[0]
          .count;
        const findMinCountArr = numrepeatInfo.filter(
          (cur) => cur.count === repMinCount,
        ); //与repMinCount最小重复数的相同的数
        const minrdm = Math.floor(Math.random() * findMinCountArr.length); //随机最小重复数字的下标
        const rdmRepNum = findMinCountArr[minrdm].val || '0'; //替换的数字
        // 替换的随机下标
        const numRepIndex = Math.floor(
          Math.random() * cv.repeatNumIndex.length,
        );
        const repI = cv.repeatNumIndex[numRepIndex];
        createId[repI] = rdmRepNum;
        numrepeatInfo[minrdm].count++;
      }
    });
  }
  return createId.toString().replace(/,/g, '');
};
